// API配置
import { getCurrentConfig } from './config.js'

// 获取当前环境配置
const currentConfig = getCurrentConfig()

// 主要API服务基地址（8080端口）
const BASE_URL = currentConfig.baseURL

// 认证服务基地址（8083端口）
const AUTH_BASE_URL = currentConfig.authBaseURL

/**
 * 统一请求封装（认证服务 8083）
 */
function requestAuth(url, options = {}) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')

    uni.request({
      url: AUTH_BASE_URL + url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'Content-Type': options.header && options.header['Content-Type'] ? options.header['Content-Type'] : 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        ...options.header
      },
      withCredentials: true, // 允许携带cookie，保证验证码的Session一致性
      success: (res) => {
        console.log('AUTH API请求成功:', url, res)
        resolve(res.data)
      },
      fail: (err) => {
        console.error('AUTH API请求失败:', url, err)
        // 尝试从 err.errMsg 中识别 401/403
        if (!err.statusCode && err && err.errMsg) {
          const lower = String(err.errMsg).toLowerCase()
          if (lower.includes('401') || lower.includes('unauthorized')) err.statusCode = 401
          if (lower.includes('403') || lower.includes('forbidden')) err.statusCode = 403
        }

        let errorMsg = '网络请求失败'
        if (err.statusCode) {
          switch (err.statusCode) {
            case 401:
              errorMsg = '登录已过期，请重新登录'
              // 清除所有可能的认证相关存储
              uni.removeStorageSync('token')
              uni.removeStorageSync('userInfo')
              uni.removeStorageSync('ai_tutor_token')
              uni.removeStorageSync('ai_tutor_user')
              uni.removeStorageSync('ai_tutor_permissions')
              uni.removeStorageSync('phone')
              uni.removeStorageSync('username')
              uni.removeStorageSync('lastLoginUser')
              
              // 清除所有本地存储（彻底清理）
              try {
                uni.clearStorageSync()
              } catch (e) {
                console.log('清除存储失败:', e)
              }
              
              uni.reLaunch({ url: '/pages/login/login' })
              break
            case 403:
              errorMsg = '没有权限访问'
              break
            case 404:
              errorMsg = '请求的资源不存在'
              break
            case 500:
              errorMsg = '服务器内部错误'
              break
            default:
              errorMsg = `请求失败: ${err.statusCode}`
          }
        } else if (err.errMsg) {
          errorMsg = err.errMsg
        }
        
        reject(new Error(errorMsg))
      }
    })
  })
}

/**
 * 统一请求封装（主服务 8080）
 */
function request(url, options = {}) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')

    uni.request({
      url: BASE_URL + url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'Content-Type': options.header && options.header['Content-Type'] ? options.header['Content-Type'] : 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        ...options.header
      },
      withCredentials: true,
      success: (res) => {
        console.log('API请求成功:', url, res)
        resolve(res.data)
      },
      fail: (err) => {
        console.error('API请求失败:', url, err)
        // 尝试从 err.errMsg 中识别 401/403
        if (!err.statusCode && err && err.errMsg) {
          const lower = String(err.errMsg).toLowerCase()
          if (lower.includes('401') || lower.includes('unauthorized')) err.statusCode = 401
          if (lower.includes('403') || lower.includes('forbidden')) err.statusCode = 403
        }

        let errorMsg = '网络请求失败'
        if (err.statusCode) {
          switch (err.statusCode) {
            case 401:
              errorMsg = '登录已过期，请重新登录'
              // 清除所有可能的认证相关存储
              uni.removeStorageSync('token')
              uni.removeStorageSync('userInfo')
              uni.removeStorageSync('ai_tutor_token')
              uni.removeStorageSync('ai_tutor_user')
              uni.removeStorageSync('ai_tutor_permissions')
              uni.removeStorageSync('phone')
              uni.removeStorageSync('username')
              uni.removeStorageSync('lastLoginUser')
              
              // 清除所有本地存储（彻底清理）
              try {
                uni.clearStorageSync()
              } catch (e) {
                console.log('清除存储失败:', e)
              }
              
              uni.reLaunch({ url: '/pages/login/login' })
              break
            case 403:
              errorMsg = '没有权限访问'
              break
            case 404:
              errorMsg = '请求的资源不存在'
              break
            case 500:
              errorMsg = '服务器内部错误'
              break
            default:
              errorMsg = `请求失败: ${err.statusCode}`
          }
        } else if (err.errMsg) {
          errorMsg = err.errMsg
        }
        
        reject(new Error(errorMsg))
      }
    })
  })
}

// 用户相关API
export const userApi = {
  // 用户登录
  login: (data) => requestAuth('/login', {
    method: 'POST',
    data: data
  }),

  // 用户注册
  register: (data) => requestAuth('/register', {
    method: 'POST',
    data: data
  }),

  // 发送验证码
  sendVerificationCode: (phone) => requestAuth('/sendVerificationCode', {
    method: 'POST',
    data: { phone }
  }),

  // 验证码登录
  loginWithVerificationCode: (data) => requestAuth('/loginWithVerificationCode', {
    method: 'POST',
    data: data
  }),

  // 获取用户信息
  getUserInfo: () => request('/user/info'),

  // 更新用户信息
  updateUserInfo: (data) => request('/user/update', {
    method: 'PUT',
    data: data
  }),

  // 修改密码
  changePassword: (data) => request('/user/changePassword', {
    method: 'PUT',
    data: data
  }),

  // 退出登录
  logout: () => request('/user/logout', {
    method: 'POST'
  })
}

// 好友相关API
export const friendApi = {
  // 获取好友列表
  getFriendList: () => request('/friend/list'),

  // 搜索用户
  searchUser: (keyword) => request('/friend/search', {
    method: 'GET',
    data: { keyword }
  }),

  // 发送好友请求
  sendFriendRequest: (data) => request('/friend/request', {
    method: 'POST',
    data: data
  }),

  // 获取好友请求列表
  getFriendRequests: () => request('/friend/requests'),

  // 处理好友请求
  handleFriendRequest: (data) => request('/friend/handleRequest', {
    method: 'PUT',
    data: data
  }),

  // 删除好友
  deleteFriend: (friendId) => request('/friend/delete', {
    method: 'DELETE',
    data: { friendId }
  })
}

// 聊天相关API
export const chatApi = {
  // 获取聊天记录
  getChatHistory: (friendId, page = 1, size = 20) => request('/chat/history', {
    method: 'GET',
    data: { friendId, page, size }
  }),

  // 发送消息
  sendMessage: (data) => request('/chat/send', {
    method: 'POST',
    data: data
  }),

  // 标记消息为已读
  markAsRead: (messageId) => request('/chat/read', {
    method: 'PUT',
    data: { messageId }
  }),

  // 获取未读消息数量
  getUnreadCount: () => request('/chat/unread/count'),

  // 获取最近聊天列表
  getRecentChats: () => request('/chat/recent')
}

// AI相关API
export const aiApi = {
  // AI对话
  chat: (data) => request('/ai/chat', {
    method: 'POST',
    data: data
  }),

  // 获取AI配置状态
  getConfigStatus: () => request('/ai/config/status'),

  // 测试AI连接
  testConnection: () => request('/ai/test'),

  // AI健康检查
  healthCheck: () => request('/ai/health')
}

// 文件上传API
export const uploadApi = {
  // 上传图片
  uploadImage: (filePath) => {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: BASE_URL + '/upload/image',
        filePath: filePath,
        name: 'image',
        header: {
          'Authorization': uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : ''
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            resolve(data)
          } catch (e) {
            reject(new Error('上传响应解析失败'))
          }
        },
        fail: (err) => {
          reject(new Error(`图片上传失败: ${err.errMsg}`))
        }
      })
    })
  },

  // 上传文件
  uploadFile: (filePath, fileName) => {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: BASE_URL + '/upload/file',
        filePath: filePath,
        name: 'file',
        formData: {
          fileName: fileName
        },
        header: {
          'Authorization': uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : ''
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            resolve(data)
          } catch (e) {
            reject(new Error('上传响应解析失败'))
          }
        },
        fail: (err) => {
          reject(new Error(`文件上传失败: ${err.errMsg}`))
        }
      })
    })
  }
}

// 系统相关API
export const systemApi = {
  // 获取系统配置
  getConfig: () => request('/system/config'),

  // 获取版本信息
  getVersion: () => request('/system/version'),

  // 系统健康检查
  healthCheck: () => request('/system/health'),

  // 获取服务器时间
  getServerTime: () => request('/system/time')
}

// 导出默认配置
export default {
  BASE_URL,
  AUTH_BASE_URL,
  request,
  requestAuth,
  userApi,
  friendApi,
  chatApi,
  aiApi,
  uploadApi,
  systemApi
}